package org.csu.mypetstore.persistence;

import java.sql.*;

/**
 * JDBC操作基类
 */
public class BaseDao {
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static final String URL="jdbc:mysql://localhost:3306/jpetstore2?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC";
    private static final String USER="root";
    private static final String PASSWORD="123456";

    /**
     * 得到Connection对象
     * @return  Connection对象
     * s
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL,USER,PASSWORD);
    }

    /**
     * 设置参数
     * @param pstmt PreparedStatement 类型对象
     * @param params Object 类型对象
     * @throws SQLException SQL语句异常
     */
    public void setParams(PreparedStatement pstmt,Object...params) throws SQLException {
        if (params!=null && params.length>0){
            for (int i=0;i<params.length;i++){
                pstmt.setObject(i+1,params[i]);
            }
        }
    }

    /**
     * 执行增删改语句
     * @param sql 预处理的SQL语句
     * @param params Object 类型对象
     * @return 数据库中受影响的行数 -1则是出现异常
     */
    public int executeUpdate(String sql,Object...params){
        Connection conn=null;
        PreparedStatement pstmt=null;
        try {
            conn=getConnection();
            pstmt=conn.prepareStatement(sql);
            setParams(pstmt,params);
            return pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return -1;
        }finally {
            closeAll(null,pstmt,conn);
        }
    }

    /**
     * 执行查询语句
     * @param pstmt PreparedStatement 类型对象
     * @param params Object 类型对象
     * @return ResultSet 类型集合
     */
    public ResultSet executeQuery(PreparedStatement pstmt,Object...params){
        try {
            setParams(pstmt,params);
            return pstmt.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

    /**
     * 释放所有资源
     * @param rs
     * @param pstmt
     * @param conn
     */
    public void closeAll(ResultSet rs,PreparedStatement pstmt,Connection conn){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (pstmt!=null){
            try {
                pstmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
